﻿SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

alter PROCEDURE [dbo].[sp_PutSOAPResponse]
@id bigint,
@Status varchar(4),
@ErrorMessage varchar(512),
@ResponseData varchar(1024),
@Sender varchar(16),
@Version varchar(4)

with encryption

 AS

declare
@SMSAnswerN varchar(1024),
@Res2 smallint, 
@Misc varchar (1024),
@Order varchar(50),
@T2 varchar(8),
@SMS_id bigint,
@TagPhone dtPhoneNumber,
@Result varchar(512),
@Answer_id bigint,
@Summary varchar(20),
@Sum bigint,
@T varchar(160),
@Operation varchar(16),
@Bonus	decimal(9,2),
--@Debit_id bigint,
@sd decimal(9,2),
@sd0 decimal(9,2),
@dt datetime,
@dtPro varchar(32),
@automat varchar(24),
@Sec varchar(19),
@Res smallint,
@PA varchar(36),
@PA0 varchar(36),
@Sender0 varchar(16),
@R varchar(160),
@RD varchar(1024),
@Service varchar(20),
@Pid bigint,
@RegN varchar(8),
@CN bigint,
@UU bigint,
@U varchar(10),
@WMTranid varchar(18),
@FinalState_id int,
@docHandle int,
@Log_id int;

DECLARE @Log_id_Table table(
    Log_ID int);

BEGIN TRY

exec sms_p.dbo.prints 'PHR 000','PutHTTPResponse to id ', @id,32
exec sms_p.dbo.prints 'PHR 013','Status:', @Status,32
exec sms_p.dbo.prints 'PHR 014','Sender:', @Sender,32
exec sms_p.dbo.prints 'PHR 015','Version:', @Version,32
exec sms_p.dbo.prints 'PHR 016','ErrorMessage',@ErrorMessage,32
exec sms_p.dbo.prints 'PHR 017','ResponseData', @ResponseData,32


set @Dt=getdate()


update  Services.dbo.SOAPRequests set 
ResponseTime=getdate(),  
[Status]=@Status, 
ResponseData=@ResponseData 
OUTPUT INSERTED.Log_ID
INTO @Log_id_Table
where [id]=@id

select @Log_id=Log_id from @Log_id_Table;

exec sms_p.dbo.prints 'PHR 077','Log_id:', @Log_id,32


if isnumeric(@status)=1
	set @res=cast(@status as smallint)
else 
	set @res=9999


update meps.dbo.AutomatLog  set  res=@Res, result=@ResponseData, datetimepro=getdate(), FinalState_id=0  where [id]=@log_id


return

/*



--insert   Services.dbo.HTTPResponse (Request_Id, Status, ErrorMessage,  Sender, Version) values (@id, @Status, @ErrorMessage, @Sender, @Version )

select @Res2=@@Error
--exec sms_p.dbo.prints_ 'PHR 016','Put HTTPResponse error:', @Res2,32



select @Misc=Misc, @SMS_id=SMS_id, @Service=[Service], @UU=Autobon  from Services.dbo.HTTPRequests 
with(nolock) where [id]=@id

--exec sms_p.dbo.prints_ 'PHR 079','Misc:', @Misc,32
--exec sms_p.dbo.prints_ 'PHR 080','Service:', @Service,32
--exec sms_p.dbo.prints_ 'PHR 081','Sms_id:', @Sms_id,32
--exec sms_p.dbo.prints_ 'PHR 082','Autobon:', @UU,32


set @U=CAST(@UU as varchar)

--if @Sender is NULL or @Sender=''
--	begin
	if @Service='PA_OTUN' set @Sender='UNET'
	else if  @Service='PA_OTIZ' set @Sender='INTERZET'
	else if  @Service='PA_OTSI' set @Sender='SILVERNET'
	else if  @Service='PA_OTDI' set @Sender='Digit'
	else if  @Service='PA_OTMO' set @Sender='MONETA'
	else set @Sender=@Service
---	end

if @Sender='PA_OTUN' set @Sender='UNET'
if @Sender='PA_OTIZ' set @Sender='INTERZET'
if @Sender='PA_OTSI' set @Sender='SILVERNET'
if @Sender='PA_OTDI' set @Sender='Digit'
if @Sender='PA_OTMO' set @Sender='MONETA'
set @sender0=@sender

---begin tran
if NOT @Status in ('0', '408','403','503','504','404','500','-1','405') 
	begin
	update  Services.dbo.HTTPRequests set ResponseTime=getdate(),  [Status]=@Status, ResponseData=@ResponseData, ExtraHeaders=@ExtraHeaders
	where [id]=@id

	
	if Upper(@sender)='WMONEY' return

	if @Sender='PA_OTAI' 
		set @ResponseData=replace(@ResponseData,'Ver="0"','Ver="2"')
/*	if UPPER(@Sender)='RMB' 
		begin
		----select @Misc=Misc, @SMS_id=SMS_id from Services.dbo.HTTPRequests where [id]=@id

		exec sp_StrParse @Misc, 1 , '*', ' ' , @Order OUTPUT , @Res2 OUTPUT
		exec sp_StrParse @Misc, @Res2 , '*', ' ' , @T2  OUTPUT , @Res2 OUTPUT
		exec sp_StrParse @Misc, @Res2 , '*', ' ' , @TagPhone  OUTPUT , @Res2 OUTPUT
		exec sp_StrParse @Misc, @Res2 , '*', ' ' , @Summary  OUTPUT , @Res2 OUTPUT

		if @Order is NULL
			set @Order=''
		exec prints 'PHR 040','GEZ number:',@Order,32
		exec prints 'PHR 041','parol:',@T2,32
		exec prints 'PHR 058','GEZ status:',@ResultStatus,32
		exec prints 'PHR 063','summary:',@summary,32

		if isnumeric(@Summary)=1 
				begin
				set @Sum=cast(@summary as bigint)
		exec prints 'PHR 063','sum:',@sum,32
				set @T=dbo.udf_DisplaySum(@Sum)
		exec prints 'PHR 063','t:',@t,32
				end
		else
				set @T='***'

		if @ResultStatus='OK' 
			begin
			set @SmsAnswerN='mobIGamer GEZ'+@order+' Zaregistriruysya na www.mobigamer.ru Parol:'+@t2    ---+' Dar:'+@T+'gez'
			----set @SmsAnswerN='mobIGamer Klan mobI GEZ'+@order+' Zaregistriruysya na wap.mobigamer.ru/'+@t2+' Dar: 50gez Otpravleno:GEZ-CMP'
			exec prints 'PHR 079','Answer:', @SmsAnswerN,32
			end		
		else
			begin
			set @SmsAnswerN='mobIGamer GEZ'+@order+' Zaregistriruysya na www.mobigamer.ru Parol:'+@t2+' Oshibka na servere mobigamer.ru:' +@ResultErrorDescription+' Otpravleno:GEZ-CMP'
			----set @SmsAnswerN='mobIGamer Klan mobI GEZ'+@order+' Zaregistriruysya na www.mobigamer.ru Parol:'+@t2+' Dar: '+@T+'gez. Oshibka na servere mobigamer.ru:' +@ResultErrorDescription+' Otpravleno:GEZ-CMP'
			----set @SmsAnswerN='mobIGamer Klan mobI GEZ'+@order+' Zaregistriruysya na wap.mobigamer.ru/'+@t2+' Dar: 50gez. Error in GEZ:' +@GEZErrorDescription+' Otpravleno:GEZ-CMP'
			----exec prints 'PHR 053','Answer:', @SmsAnswerN,32
			end
		end		

	else if UPPER(@Sender)='SKYSPELL' 
		begin
		select @Misc=Misc, @SMS_id=SMS_id from Services.dbo.HTTPRequests where [id]=@id

		exec sp_StrParse @Misc, 1 , '~', ' ' , @TagPhone OUTPUT , @Res2 OUTPUT   
		exec sp_StrParse @Misc, @Res2 , '~', ' ' , @Order OUTPUT , @Res2 OUTPUT   

		exec prints 'PHR 114','Phone number:',@TagPhone,32


		if @ResultStatus='OK' 
			begin
			declare @s1 varchar(9), @s2 varchar(9)
			set @s2=CAST(@id as varchar)
			if len(@s2)=3 
				set @S1='000'
			else if len(@s2)=4
				set @S1='00'
			else if len(@s2)=5
				set @S1='0'
			else 
				set  @s1=''
			set @SmsAnswerN='Сообщение отправлено. Знаков:' +@order+'. Справки на  http://www.sms2sky.com. Учетный номер: '+'119'+@S1+@s2+'.'
			end		
		else
			begin
			set @SmsAnswerN='Сообщение не отправлено: '+@ResultErrorDescription
			end
		exec prints 'PHR 120','Answer:', @SmsAnswerN,32
		end		

	else 
*/
	if UPPER(@Sender)='LANCK' 
		begin
		select @Misc=Misc, @SMS_id=SMS_id from Services.dbo.HTTPRequests where [id]=@id
		exec sms_p.dbo.prints 'PHR 128','Misc:', @Misc,32
		exec sp_StrParse @Misc, 1 , '~', ' ' , @TagPhone OUTPUT , @Res2 OUTPUT   
		exec sp_StrParse @Misc, @Res2 , '~', ' ' , @Summary OUTPUT , @Res2 OUTPUT   

		--exec prints 'PHR 114','Phone number:',@TagPhone,32


		if @ResultStatus='' 
			begin
			set @SmsAnswerN='LANCK-Telecom. Оплачено: '+@Summary+' руб.  Тел. '+@TagPhone+'. Платеж ' +CAST(@id as varchar)+' Справки на  http://www.sms4pay.net'
			end		
		else
			begin
			set @SmsAnswerN='Error: '+@ResultErrorDescription
			end
		exec prints 'PHR 120','Answer:', @SmsAnswerN,32
		end		

/*	else if UPPER(@Sender)='PES' 
		begin
			здесь ответ не ставится, TAGPHONE ?????
		select @Misc=Misc, @SMS_id=SMS_id from Services.dbo.HTTPRequests where [id]=@id
		exec sms_p.dbo.prints 'PHR 149','Misc:', @Misc,32

		if @ResultStatus='' 
			begin
			set @SmsAnswerN='PES 1:   ' +CAST(@id as varchar)
			end		
		else
			begin
			set @SmsAnswerN='Error: '+@ResultErrorDescription
			end
		exec prints 'PHR 159','Answer:', @SmsAnswerN,32

		exec prints 'PHR 160','sesion_id:',@SMS_id,32
		end		
*/	else if UPPER(@Sender) in ('TELIX' , 'MONETA', 'PE_TELIX')
		begin

		set @R='Error'
		if @Status='200'
			begin
-----			select @Misc=Misc, @SMS_id=SMS_id from Services.dbo.HTTPRequests where [id]=@id
			exec sp_StrParse @Misc, 1 , '*', ' ' , @Operation OUTPUT , @Res2 OUTPUT
			exec sp_StrParse @Misc, @Res2 , '*', ' ' , @T2  OUTPUT , @Res2 OUTPUT
			if isNumeric(@t2)=1
				set @sd=CAST(@T2 as decimal(9,2))
			else 
				set @Sd=NULL
/*			exec sp_StrParse @Misc, @Res2 , '*', ' ' , @T2  OUTPUT , @Res2 OUTPUT
			if isNumeric(@t2)=1
				set @Bonus=CAST(@T2 as decimal(9,2))
			else 
				set @Bonus=NULL
*/
			exec sp_StrParse @Misc, @Res2 , '*', ' ' , @PA  OUTPUT , @Res2 OUTPUT

			if charindex('RESULT: 0',upper(@ExtraHeaders)) > 0 
				begin
				exec prints 'PHR 187','Telix/moneta:','Result: 0',32
				set @Dt=getdate()
				set @Res=0
/*
				exec sms_p.[dbo].[sp_PutDebit] @Input_id=@Sms_id, @Input_Table='AutomatLog', @Payee=@Sender, @Operation=@Operation, 
					@Sum=@sd, @PA=@PA, @Bonus1=0, @Bonus2=0, @Bonus3=0, @ReestrDate=@dt, @U=@U,
					@Debit_id=@Debit_id OUTPUT, @Res=@res2 OUTPUT, @Result=@T2 OUTPUT


				exec prints 'PHR 189','Telix/moneta debit:',@Debit_id,32
				if @Res2<>0
					begin
					exec prints 'PHR 191','Debit log error:',@Res2,32
					exec prints 'PHR 193','Debit log error:',@T2,32
					set @res=4443
					end
				else
*/
--					begin
					set @R='Уведомление доставлено'
					set @res=0
--					end
				end		
			else	
				begin
				set @res=4442
				set @R=@ResponseData
				end
	
			end
		else			
			set @Res=4444
			
		exec sms_p.dbo.sp_SetAutomatResult00 @id=@SMS_id, @Res=@Res, @Result=@R, @ResultServiceTime=@Dt, 
			@Service=@Service

		end
	else if @Sender in ('UNET','PA_OTUN2', 'INTERZET','PA_OTUNTEL') 
		begin
		exec prints 'PHR 244','Response data:',@ResponseData,32
		set @Dt=getdate()
		exec sp_StrParse @Misc, 1 , '*', ' ' , @PA OUTPUT , @Res2 OUTPUT
		exec sp_StrParse @Misc, @Res2 , '*', ' ' , @T2  OUTPUT , @Res2 OUTPUT
			if isNumeric(@t2)=1
				set @sd=CAST(@T2 as decimal(9,2))
			else 
				set @Sd=NULL

		if Charindex('status=0',@ResponseData)>0 
			begin
			set @Res=0
			set @R='Уведомление доставлено' 
/*
			exec sms_p.[dbo].[sp_PutDebit] @Input_id=@Sms_id, @Input_Table='AutomatLog', @Payee=@Sender, @Operation=@Service, 
				@Sum=@sd, @PA=@PA, @Bonus1=0, @Bonus2=0, @Bonus3=0, @ReestrDate=@dt, @U=@U,
				@Debit_id=@Debit_id OUTPUT, @Res=@res2 OUTPUT, @Result=@T2 OUTPUT

				exec prints 'PHR 189','Unet debit:',@Debit_id,32
*/			end
		else if Charindex('status=1',@ResponseData)>0 
			begin
			set @Res=0
			set @R='Платеж с этим идентификатором был совершен ранее.' 
/*
			if not exists(select [id] from cards.dbo.debit with(nolock) where input_Table='AutomatLog' and input_id=@sms_id) 
				begin
				exec sms_p.[dbo].[sp_PutDebit] @Input_id=@Sms_id, @Input_Table='AutomatLog', @Payee=@Sender, @Operation=@Service, 
					@Sum=@sd, @PA=@PA, @Bonus1=0, @Bonus2=0, @Bonus3=0, @ReestrDate=@dt, @U=@U,
					@Debit_id=@Debit_id OUTPUT, @Res=@res2 OUTPUT, @Result=@T2 OUTPUT
				exec prints 'PHR 189','Unet debit:',@Debit_id,32
				end
*/
			end
		else if Charindex('status=-100',@ResponseData)>0 
			begin
			set @Res=1422
			set @R='Проблемы с идентификацией.' 
			end
		else if Charindex('status=-1',@ResponseData)>0 
			begin
			set @Res=1421
			set @R='Неверный идентификатор счета.' 
			end
		else if Charindex('status=-3',@ResponseData)>0 
			begin
			set @Res=1423
			set @R='Неверные параметры' 
			end
		else if Charindex('status=-4',@ResponseData)>0 
			begin
			set @Res=1424
			set @R='Неверный тип запроса' 
			end
		else if Charindex('status=-5',@ResponseData)>0 
			begin
			set @Res=1425
			set @R='Неверный формат суммы' 
			end
		else
			begin
			set @Res=1621
			set @R='Уведомление не доставлено: '+@ResponseData
			end

		exec sms_p.dbo.sp_SetAutomatResult00 @id=@SMS_id, @Res=@Res, @Result=@R, @ResultServiceTime=@Dt, 
			@Service=@Service
	
		end
	else if @Sender='SILVERNET_old' 
		begin
		exec prints 'PHR 320','Response data:',@ResponseData,32
		set @Dt=getdate()
		exec sp_StrParse @Misc, 1 , '*', ' ' , @PA OUTPUT , @Res2 OUTPUT
		exec sp_StrParse @Misc, @Res2 , '*', ' ' , @T2  OUTPUT , @Res2 OUTPUT
			if isNumeric(@t2)=1
				set @sd=CAST(@T2 as decimal(9,2))
			else 
				set @Sd=NULL

		if Charindex('Res="0"',@ResponseData)>0 
			begin
			set @Res=0
			set @R='Уведомление доставлено' 
/*
			exec sms_p.[dbo].[sp_PutDebit] @Input_id=@Sms_id, @Input_Table='AutomatLog', @Payee=@Sender, @Operation=@Service, 
				@Sum=@sd, @PA=@PA, @Bonus1=0, @Bonus2=0, @Bonus3=0, @ReestrDate=@dt, @U=@U,
				@Debit_id=@Debit_id OUTPUT, @Res=@res2 OUTPUT, @Result=@T2 OUTPUT

				exec prints 'PHR 337','Silvernet debit:',@Debit_id,32
*/
			end
		else if Charindex('Res="-30"',@ResponseData)>0 
			begin
			set @Res=0
			set @R='Платеж с этим идентификатором был совершен ранее.' 
/*
			if not exists(select [id] from cards.dbo. with(nolock) where input_Table='AutomatLog' and input_id=@sms_id) 
				begin
				exec sms_p.[dbo].[sp_PutDebit] @Input_id=@Sms_id, @Input_Table='AutomatLog', @Payee=@Sender, @Operation=@Service, 
					@Sum=@sd, @PA=@PA, @Bonus1=0, @Bonus2=0, @Bonus3=0, @ReestrDate=@dt, @U=@U,
					@Debit_id=@Debit_id OUTPUT, @Res=@res2 OUTPUT, @Result=@T2 OUTPUT
				exec prints 'PHR 348','Silvernet debit:',@Debit_id,32
				end
*/
			end
		else if Charindex('Res="-13"',@ResponseData)>0 
			begin
			set @Res=1421
			set @R='Неверный идентификатор счета' 
			end
		else if Charindex('Res="-1"',@ResponseData)>0 
			begin
			set @Res=1425
			set @R='Неверный формат суммы' 
			end
		else
			begin
			set @Res=1621
			set @R='Уведомление не доставлено: '+@ResponseData
			end

		exec sms_p.dbo.sp_SetAutomatResult00 @id=@SMS_id, @Res=@Res, @Result=@R, @ResultServiceTime=@Dt, 
			@Service=@Service
			
		end
	else if Charindex('encoding="utf-8"',lower(@ResponseData))>0
		begin
		set @ResponseData=replace(@ResponseData,'”','"')
		set @ResponseData=replace(@ResponseData,'is <','is less ')
		set @ResponseData=replace(@ResponseData,'or >','or more ')
		exec prints 'PHR 445','Response data:',@ResponseData,32
		set @Res=9777


		exec sp_StrParse @Misc, 1 , '*', NULL , @PA0 OUTPUT , @Res2 OUTPUT
		exec sp_StrParse @Misc, @Res2 , '*', ' ' , @T2  OUTPUT , @Res2 OUTPUT
			if isNumeric(@t2)=1
				set @sd0=CAST(@T2 as decimal(9,2))
			else 
				set @Sd0=NULL
		
		declare @k int
		set @k=Charindex('</Response>',@ResponseData)
		set @k=@k+10
		if (Len(@ResponseData) > @k)
			set @ResponseData=substring(@ResponseData,1,@k)


		EXEC sp_xml_preparedocument @docHandle OUTPUT, @ResponseData
		
		SELECT @Sender=Sender
			FROM OPENXML(@docHandle, N'/Response') 
			WITH (Sender nvarchar(12)  )

		if @Sender is NULL or @Sender=''
					set  @sender=@Sender0

		declare  @sRes nvarchar(9), @sID nvarchar(18), @sSum nvarchar(12)
----DateTime="2008-08-14 20:08:47"
		SELECT @RD=Result, @sRes=Res, @sid=ID, @PA=[Order], @sSum=[Sum], @DtPro=[DateTime], @WMTranId=[WMTranId]
			FROM OPENXML(@docHandle, N'/Response/Payment') 
			WITH (Result nvarchar(512) , Res nvarchar(9), ID nvarchar(18), [Order] nvarchar(36), [Sum] nvarchar(12), [DateTime] varchar(32),[WMTranId] varchar(18) )
		exec sp_xml_removedocument @docHandle

		if isnumeric(@sRes)=1
			set @Res=CAST(@sRes as int)
		else
			set @Res=-99

		if isnumeric(@sID)=1
			set @Pid=CAST(@sID as bigint)
		else
			set @Pid=-1

		if isnumeric(@sSum)=1
			set @Sd=CAST(@sSum as decimal(9,2))
		else
			set @Sd=NULL

		
		if @res<>0 
				begin
				set @res=@Res-100
				end


		if ((@RD is NULL) or (ltrim(@RD)='') ) or (rtrim(ltrim(@RD))='_') 
				set @RD=dbo.udf_Result_2_03(@res)
		
		if (@Pid is not NULL) and (@Pid<>-1) and (@PID<>0)
				set @RD=@RD +' # '+ CAST(@PID as varchar)


		if @Res=0
			begin
				if (@PA is null) or (ltrim(rtrim(@PA))='')
					set @PA=@PA0
				else if (@PA<>@PA0) and (@PA0<>'7'+@PA)
					begin
					Set @RD='Номер счета не подтвержден '+@RD+' pa:'+@pa+' pa0:'+@pa0
					Set @Res=9771
					end

			if @sd is NULL
					set @Sd=@sd0
			else  if @Sd<>@SD0  and @Service not in ('PA_OTVIRTRU','PE_YOUSAFE')
					begin
					Set @RD='Сумма оплаты не подтверждена '+@RD
					Set @Res=9772
					end
			end

		if (@Res = -130) 
				begin
				set @Res=0
				set @Rd=@Rd+' (дубликат уведомления)'
				end
		
		
			exec sms_p.dbo.sp_SetAutomatResult00 @id=@SMS_id,  @Res=@Res, @Result=@RD, @ResultServiceTime=@Dt, 
			@Service=@Service


/*		if (@Res=0) and  (@Service<>'PA_OTMTS') and  (@Service<>'PE_BEE')
				if not exists(select [id] from cards.dbo.debit with(nolock) where input_Table='AutomatLog' and input_id=@sms_id) 
						begin
						exec sms_p.[dbo].[sp_PutDebit] @Input_id=@Sms_id, @Input_Table='AutomatLog', @Payee=@Sender, @Operation=@Service, 
					@Sum=@sd, @PA=@PA, @Bonus1=0, @Bonus2=0, @Bonus3=0, @ReestrDate=@dt, @U=@U, 
					@Debit_id=@Debit_id OUTPUT, @Res=@res2 OUTPUT, @Result=@T2 OUTPUT
					exec prints 'PHR 390','Set debit:',@Debit_id,32
						end
*/
		end
	else if Charindex('<Response',@ResponseData)>0  and Charindex('ver="2"',@ResponseData)>0  
--- ---------------------------------------------------------------
		begin
		set @ResponseData=replace(@ResponseData,'”','"')
		set @ResponseData=replace(@ResponseData,'is <','is less ')
		set @ResponseData=replace(@ResponseData,'or >','or more ')
		exec prints 'PHR 373','Response data:',@ResponseData,32
		set @Res=9777


		exec sp_StrParse @Misc, 1 , '*', NULL , @PA0 OUTPUT , @Res2 OUTPUT
		exec sp_StrParse @Misc, @Res2 , '*', ' ' , @T2  OUTPUT , @Res2 OUTPUT
			if isNumeric(@t2)=1
				set @sd0=CAST(@T2 as decimal(9,2))
			else 
				set @Sd0=NULL
		
		if Charindex('<?xml',@ResponseData)=0
				set @ResponseData='<?xml version="1.0" encoding="Windows-1251"?>'+@ResponseData
		set @k=Charindex('</Response>',@ResponseData)
		set @k=@k+10
		if (Len(@ResponseData) > @k)
			set @ResponseData=substring(@ResponseData,1,@k)



		EXEC sp_xml_preparedocument @docHandle OUTPUT, @ResponseData
		
		SELECT @Sender=Sender
			FROM OPENXML(@docHandle, N'/Response') 
			WITH (Sender nvarchar(12)  )

		if @Sender is NULL or @Sender=''
					set  @sender=@Sender0

----DateTime="2008-08-14 20:08:47"
		SELECT @RD=Result, @sRes=Res, @sid=ID, @PA=[Order], @sSum=[Sum], @DtPro=[DateTime], @WMTranId=[WMTranId]
			FROM OPENXML(@docHandle, N'/Response/Payment') 
			WITH (Result nvarchar(512) , Res nvarchar(9), ID nvarchar(18), [Order] nvarchar(36), [Sum] nvarchar(12), [DateTime] varchar(32),[WMTranId] varchar(18) )
		exec sp_xml_removedocument @docHandle

		if isnumeric(@sRes)=1
			set @Res=CAST(@sRes as int)
		else
			set @Res=-99

		if isnumeric(@sID)=1
			set @Pid=CAST(@sID as bigint)
		else
			set @Pid=-1

		if isnumeric(@sSum)=1
			set @Sd=CAST(@sSum as decimal(9,2))
		else
			set @Sd=NULL

		
		if @res<>0 
				begin
				if @Service='PA_OTMTS'
							set @res=@Res-300
				else 
							set @res=@Res-100

				if @Service='PA_OTORIFL' and @Res=-210
							begin
							set @res=1325
							set @RD='Орифлэйм. Платеж принят к выполнению. Для уточнения статуса надо повторить.'
							end
				end

		if @Service='PA_OTMTS'						
						if isDate(@dtPro)=1
								set @dt=CONVERT(datetime,@dtPro,120)

		if @Service='PE_YOTA' and  (rtrim(ltrim(@RD))='Неверное значение номера платежа') 
				begin
				set @RD='YOTA. Платеж принят к выполнению. Необходимо повторить.'
				set @res=1326
				end		

		if @Service='PA_OTPIN' and  (rtrim(ltrim(@RD)) like 'Временной интервал от 01 до 03 часов%') 
				begin
				set @RD=@RD+ ' Утром будет автоповтор.'
				set @res=1326
				end		

		if ((@RD is NULL) or (ltrim(@RD)='') ) or (rtrim(ltrim(@RD))='_') 
				set @RD=dbo.udf_Result_2_03(@res)
		
		if (@Pid is not NULL) and (@Pid<>-1) and (@PID<>0)
				set @RD=@RD +' # '+ CAST(@PID as varchar)

		if (@WMTranid is not NULL) 
				set @RD=@RD +' # '+ CAST(@WMTranid  as varchar)

		if @Res=0
			begin
			if @Service not in ('PA_OTDOM'	,'JKX','JKXP','JKX2','JKX2P','KATRINA','PA_OTVIRTRU','PA_OTISEIN','PA_OTISETV')							
				begin
				if (@PA is null) or (ltrim(rtrim(@PA))='')
					set @PA=@PA0
				else if (@PA<>@PA0) and (@PA0<>'7'+@PA)
					begin
					Set @RD='Номер счета не подтвержден '+@RD+' pa:'+@pa+' pa0:'+@pa0
					Set @Res=9771
					end
				end
			else if @Service in ('PA_OTISEIN','PA_OTISETV')							
				begin
				if (isnumeric(@PA)=1) and (isnumeric(@Pa0)=1)
					begin
					if (cast(@PA as int)<>cast(@PA0 as int))
						begin
						Set @RD='Номер счета не подтвержден '+@RD+' pa:'+@pa+' pa0:'+@pa0
						Set @Res=9771
						end
					end
				else if (@PA<>@PA0) 
					begin
					Set @RD='Номер счета не подтвержден '+@RD+' pa:'+@pa+' pa0:'+@pa0
					Set @Res=9771
					end
				end
			

			if @sd is NULL
					set @Sd=@sd0
			else  if @Sd<>@SD0  and @Service not in ('PA_OTVIRTRU','PE_YOUSAFE')
					begin
					Set @RD='Сумма оплаты не подтверждена '+@RD
					Set @Res=9772
					end
			end

		if (@Res = -130) 
				begin
				set @Res=0
				set @Rd=@Rd+' (дубликат уведомления)'
				end
		
		
			exec sms_p.dbo.sp_SetAutomatResult00 @id=@SMS_id,  @Res=@Res, @Result=@RD, @ResultServiceTime=@Dt, 
			@Service=@Service


/*		if (@Res=0) and  (@Service<>'PA_OTMTS') and  (@Service<>'PE_BEE')
				if not exists(select [id] from cards.dbo.debit with(nolock) where input_Table='AutomatLog' and input_id=@sms_id) 
						begin
						exec sms_p.[dbo].[sp_PutDebit] @Input_id=@Sms_id, @Input_Table='AutomatLog', @Payee=@Sender, @Operation=@Service, 
					@Sum=@sd, @PA=@PA, @Bonus1=0, @Bonus2=0, @Bonus3=0, @ReestrDate=@dt, @U=@U, 
					@Debit_id=@Debit_id OUTPUT, @Res=@res2 OUTPUT, @Result=@T2 OUTPUT
					exec prints 'PHR 390','Set debit:',@Debit_id,32
						end
*/
		end
	else 	
		begin
		if charindex('NO DATA',Upper(@ResponseData)) > 0
			begin
			set @Res=9773		-- в ответе нет данных
			set @ResponseData='От получателя платежа получен пустой ответ'
			end
		else
			begin
			set @Res=9774   -- ответ не соответствует протоколу
			set @ResponseData='Ответ не соответствует протоколу:'+substring(@ResponseData,1,990)
			end 
		exec sms_p.dbo.sp_SetAutomatResult00 @id=@SMS_id, @Res=@Res, @Result=@ResponseData, @ResultServiceTime=@Dt, 
				@Service=@Service
		exec prints 'PHR 163','SMS_id:',@SMS_id,32

		end



	set @Answer_id=NULL
	exec prints 'PHR 112','TagPhone:',@TagPhone,32
	exec prints 'PHR 113','SmsAnswerN:',@SmsAnswerN,32

	if Substring(@TagPhone,1,3) <>'100'  and @smsAnswerN is NOT null
		begin
 		exec sp_InsToAnswers  @SMS_id, @TagPhone, @SmsAnswerN, 1, 		'PAY', 0, @Result OUTPUT, @Answer_id OUTPUT
		exec prints 'PHR 114','@Result:',@Result,32
		exec prints 'PHR 115','@Answer_id:',@Answer_id,32
		if @Answer_id<>NULL
			begin
			---commit tran
			exec prints 'PHR 116','Answer:', @Answer_id ,32
			end
		else			begin
			---rollback tran
			exec prints 'PHR 117','Set PUTHTTPResponse rollbacked, sms_id:', @sms_id ,32
			set @T='Set PUTHTTPResponse rollbacked, sms_id:'+Cast(@sms_id as varchar)+' Request_Id:'+Cast(@Id as varchar)+' Sender:'+@Sender  
			exec sp_SetNotification 'RollBack', @T
			end
		end

	end
else
	begin
	if @Service in ('PA_OTUN','PA_OTUN2')
		begin
		set @Res=0
		set @R='Уведомление отправлено по почте / http status='+@Status
--		exec sms_p.[dbo].[PutPaymentToDebit] @id=@sms_id
		end
	else
		begin
		if @Status in ('500', '503')
			begin
			set @Res=1624
			set @R='Уведомление не доставлено: status='+@Status+' Ошибка в скрипте получателя'
			end
		else if @Status = '403'
			begin
			if @Service ='PA_OTVKONT'
				begin
				set @Res=1628
				set @R='Уведомление не доставлено: status='+@Status+' Нет доступа (В контакте)'
				end
			else
				begin
				set @Res=1626
				set @R='Уведомление не доставлено: status='+@Status+' Нет доступа'
				end
			end
		else if @Status = '405'
			begin
			set @Res=1627
			set @R='Уведомление не доставлено: status='+@Status+' Method Not Allowed'
			end
		else if @Status = '404'
			begin
			set @Res=1623
			set @R='Уведомление не доставлено: status='+@Status+' Скрипт получателя не найден'
			end
		else if @Status = '-1'
			begin
			set @Res=1622
			set @R='Уведомление не доставлено: status='+@Status+' или ответ не получен'
			end
		else
			begin
			set @Res=1625
			set @R='Уведомление не доставлено: status='+@Status
			end
		end
	exec sms_p.dbo.sp_SetAutomatResult00 @id=@SMS_id, @Res=@Res, @Result=@R, @ResultServiceTime=@Dt, 
		@Service=@Service
	end
*/
END TRY
BEGIN CATCH
print @@Trancount
IF @@TRANCOUNT > 0 
			ROLLBACK TRANSACTION;	

exec meps.Control.usp_LogError @T OUT;	-- диагностика ошибки

set @Result='PutHTTPResponse: '+CAST(@log_id as varchar) +' '+@T
set @Res=10000+@Res

select @FinalState_id=FinalState from meps.dbo.TB with(nolock) where Code=@res	

update meps.dbo.AutomatLog  set  res=@res, result=@Result, datetimepro=getdate(), FinalState_id=@FinalState_id  where [id]=@log_id


END CATCH

/*
DECLARE	@return_value int

EXEC	@return_value = [dbo].[sp_PutSOAPResponse]
		@id = 2,
		@Status = N'0',
		@ErrorMessage = N'Запрос прошел успешно',
		@ResponseData = N'No data',
		--@Extra = N'No extra',
		@Sender = N'sender',
		@Version = N'123'

SELECT	'Return Value' = @return_value

*/

GO
GO
